from datetime import timedelta
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

from www import models


def fetch_course_info(request):
    token = request.GET.get("token")
    if token != settings.API_TOKEN:
        return JsonResponse({"code": 1, "error": "签名失败"})

    course_name = request.GET.get("course")
    if not course_name:
        return JsonResponse({"code": 1})

    instance = models.Course.objects.filter(title=course_name).first()
    if not instance:
        return JsonResponse({"code": 0, 'data': {}})

    # 课程下的所有：章节+视频
    queryset = models.Chapter.objects.filter(course_id=instance.id).order_by("order", 'video__order') \
        .values("id", 'title', "video__id", "video__title", 'video__duration')

    chapter_dict = {}
    for row in queryset:
        chapter_title, chapter_id = row['title'], row['id']
        video_title, video_id = row['video__title'], row['video__id']

        if chapter_title not in chapter_dict:
            chapter_dict[chapter_title] = {
                "chapter_id": chapter_id,
                "video_list": [video_title] if video_id else []
            }
        else:
            chapter_dict[chapter_title]['video_list'].append(video_title)

    context = {
        "course_id": instance.id,
        "chapter_dict": chapter_dict
    }
    return JsonResponse({"code": 0, 'data': context})


@csrf_exempt
def create_chapter(request):
    token = request.GET.get("token")
    if token != settings.API_TOKEN:
        return JsonResponse({"code": 1, "error": "签名失败"})

    try:
        course_id = request.POST.get("course_id")
        title = request.POST.get("title")
        order = request.POST.get("order")
        instance = models.Chapter.objects.create(course_id=course_id, title=title, order=order)
        return JsonResponse({"code": 0, 'data': instance.id})
    except Exception as e:
        return JsonResponse({"code": 1, "error": str(e)})


@csrf_exempt
def create_video(request):
    token = request.GET.get("token")
    if token != settings.API_TOKEN:
        return JsonResponse({"code": 1, "error": "签名失败"})

    try:
        course_id = request.POST.get("course_id")
        chapter_id = request.POST.get("chapter_id")
        vid = request.POST.get("vid")
        title = request.POST.get("title")
        order = request.POST.get("order")
        duration = request.POST.get("duration")

        models.Video.objects.create(
            course_id=course_id, chapter_id=chapter_id, vid=vid, title=title,
            order=order, duration=duration
        )
        return JsonResponse({"code": 0})
    except Exception as e:
        return JsonResponse({"code": 1, "error": str(e)})
